<?php

namespace App\Http\Controllers\Account;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Components\UserComponent;

use DB;
use App\Models\AccountBillModel;

/*
* 获取绑定的提现账户
*/
class BillListController extends AccountController{

    public function __construct(){
         parent::__construct();
    }
    
    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            return $this->bill_list($request);
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /*
    * 获取绑定的提现账户
    * @param $user_id 用户id
    * @return 
   */
    public function bill_list(Request $request){
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];

        $page_index  = intval($request->input('page_index'))?intval($request->input('page_index')):0;

        $limit = 10;
        $offest = $page_index * $limit;

        $billList = AccountBillModel::select([
            'order_no',
            'channel',
            'amount',
            'subject',
            'body',
            'currency',
            'status',
            'type',
            'bill_time',
        ])
        ->where('user_id',$user_id)
        ->where('status','succeeded')
        ->skip($offest)
        ->take($limit)
        ->orderBy('bill_time', 'desc')
        ->get()->toArray();

        if ($billList) {
            // $this->update($user_id);
            foreach ($billList as &$bill) {
                $bill['amount'] = number_format(floatval($bill['amount'] / 100),2);
                $bill['amount'] = ($bill['amount'] > 0)?("+$bill[amount]"):($bill['amount']);
            }
            $data = $billList;
            $count = count($data);
            return $this->json('1','',$data,compact('count'));   
        }else{
            return $this->json('0','没有记录');
        }
    }

    private function update($user_id){
        /*更新战队钱包*/
        $bill_amount = DB::table('account_bill')->where(['user_id'=>$user_id,'status'=>'succeeded'])->sum('amount');

        DB::table('user_account')->where('user_id',$user_id)->update(['balance'=>$bill_amount]);
    }
}
